package com.zenithmind.common.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * Redis配置类
 * 用于配置Redis的序列化方式和缓存管理器
 */
@Configuration
@EnableCaching
public class RedisConfig {

    // Redis服务器地址
    @Value("${spring.redis.host:localhost}")
    private String redisHost;

    // Redis服务器端口
    @Value("${spring.redis.port:6379}")
    private int redisPort;

    // Redis服务器密码
    @Value("${spring.redis.password:}")
    private String redisPassword;

    /**
     * 配置自定义RedisTemplate，使用GenericJackson2JsonRedisSerializer进行序列化
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);
        
        // 创建支持Java 8日期时间API的ObjectMapper
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule());
        // 禁用在遇到空Bean时抛出异常的特性
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);

        // 使用上述ObjectMapper创建序列化器
        GenericJackson2JsonRedisSerializer jsonSerializer =
            new GenericJackson2JsonRedisSerializer(objectMapper);
        
        // 设置key和value的序列化规则
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(jsonSerializer);
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(jsonSerializer);
        
        template.afterPropertiesSet();
        return template;
    }

    /**
     * 配置缓存管理器
     * 解决缓存雪崩：通过设置不同的过期时间，错开缓存过期时间
     */
    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        // 生成随机数，用于错开缓存时间
        Random random = new Random();
        
        // 默认配置
        RedisCacheConfiguration defaultConfig = RedisCacheConfiguration.defaultCacheConfig()
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()))
                .entryTtl(Duration.ofMinutes(30)) // 默认30分钟过期
                .disableCachingNullValues(); // 不缓存空值，防止缓存穿透
        
        // 为不同的缓存空间设置不同的过期时间，错开缓存过期时间，防止缓存雪崩
        Map<String, RedisCacheConfiguration> configMap = new HashMap<>();
        
        // 用户缓存，过期时间为25-35分钟之间随机
        configMap.put("userCache", defaultConfig.entryTtl(
                Duration.ofMinutes(25 + random.nextInt(10))));
        
        // 角色缓存，过期时间为55-65分钟之间随机
        configMap.put("roleCache", defaultConfig.entryTtl(
                Duration.ofMinutes(55 + random.nextInt(10))));
        
        // 权限缓存，过期时间为115-125分钟之间随机
        configMap.put("permissionCache", defaultConfig.entryTtl(
                Duration.ofMinutes(115 + random.nextInt(10))));
        
        // 菜单缓存，过期时间为85-95分钟之间随机
        configMap.put("menuCache", defaultConfig.entryTtl(
                Duration.ofMinutes(85 + random.nextInt(10))));
        
        // 创建缓存管理器
        return RedisCacheManager.builder(connectionFactory)
                .cacheDefaults(defaultConfig)
                .withInitialCacheConfigurations(configMap)
                .build();
    }
    
    /**
     * 配置Redisson客户端
     * 用于分布式锁等高级功能
     */
    @Bean
    @ConditionalOnMissingBean
    public RedissonClient redissonClient() {
        Config config = new Config();
        String address = "redis://" + redisHost + ":" + redisPort;
        
        // 单节点模式
        if (redisPassword != null && !redisPassword.isEmpty()) {
            config.useSingleServer()
                    .setAddress(address)
                    .setPassword(redisPassword)
                    .setDatabase(0);
        } else {
            config.useSingleServer()
                    .setAddress(address)
                    .setDatabase(0);
        }
        
        return Redisson.create(config);
    }
} 